/*
 * EasyUI 排版插件
 * Create by Georeg 
 * 2016-5-25
 */
//---------------------------------------------------------------
//对控件数组在指定DOM中进行布局
//initControls(ctls,pid)
//	ctls:控件数组
//	pid:DOM id,空则取<body>
//---------------------------------------------------------------
//对控件在指定DOM中进行布局（控件有递归层次，不一定是一个控件）
//initControl(ctl,pid)
//	ctls:控件
//	pid:DOM id,空则取<body>
//---------------------------------------------------------------
//根据指定DOM为根节点生成布局控件数组，
//initLayout（layout,pid）
//	pid:DOM id,空则取<body>
//	layout:布局设置
//---------------------------------------------------------------
//将数据绑定到非窗口输入控件
//loadData(pid,data)
//	pid:DOM id,空则取<body>
//	data:JSON结构对象数据
//
////////////////////////////////////
//数据结构说明
////////////////////////////////////
//控件定义结构
//control :  {
//	id : 'dom id',	 			（必需） --DOM ID  
//  caption : '联系电话',				--标题
//	captionVisible:false,					--是否显示标题（默认TRUE）
//	colspan : 2,						--布局占位数，默认 1
//	isExternal : true,    				--外部控件，非EasyUI 控件( 默认false)
//	type : 'easyui-datebox',	（必需） --控件类型，EasyUI控件用其Class名， 普通DOM用其DOM名，如“DIV”
//	style : " padding: 15px; ",			--样式表
//	attr : " mothed='post' ",			--Dom 特征
//  InnerHTML:"",						--非EasyUI控件插入的HTML文本
//	option : {width : 10,height : 10},	--EasyUI 件参数对象，参见具体控件API
//	layout : {}	,						--布局定义
//	controls : []						--布局控件数组
//  }
//---------------------------------------------------------------
//布局定义结构
//layout : {
//	captionWidth : 80,					--标题宽度   			    ( 默认80)
//  captionSuffix:"",					--标题后缀
//  textAlign:"right",					--标题位置（left,right,center） 默认 right
//	fieldWidth : 200,					--字段宽度				( 默认200)
//	fieldHeight : 28,					--默认字段控件高度                   ( 默认 EasyUI 控件高度)
//	rowHeight : 30,						--行布局高度                               	( 默认 28)
//	columns : 2,						--布局列数                                   	( 默认2)
//	controls : []						--布局控件数组
//  }
//---------------------------------------------------------------
$.namespace('EasyUIInit');
EasyUIInit = function() {
	return {
		initControls : function(ctls, pid) {
			
			
			if (pid == undefined || pid == "")
				pid = 'body';
			
			for (var i = 0; i < ctls.length; i++)
			{
				this.initControl(ctls[i], pid);
			}
				
		},
		initControl : function(ctl, pid) {
			if (pid == undefined || pid == "")
				pid = 'body';
			// 设置默认选项
			ctl.option = this.initOption(ctl.type, ctl.option);

			if (ctl.layout != undefined) {
				ctl.controls = this.layControls(ctl.id, ctl.layout);
				ctl.layout = undefined;
			}

			// 如果不是外部控件，则生成EasyUI控件
			if (ctl.isExternal == undefined)
				ctl.isExternal = false;

			this.initDom(ctl, pid);
			// 生成子元素
			if (ctl.controls != undefined) {
				this.initControls(ctl.controls, ctl.id);

			}

			if (!ctl.isExternal) {

				var sMothed = ctl.type.replace(/easyui-/, '');
				if (pid != 'body')
					pid = "#" + pid;
				//console.log(ctl.caption + ctl.option.width);
				try {
					eval(' $("' + pid + '").find("*[id=' + ctl.id + ']").'
						+ sMothed + '(ctl.option);');

					//eval(' $("#" + ctl.id).' + sMothed + '(ctl.option);');
				}catch(e){ ;}
			}

		},
		initLayout : function(layout, pid) {
			this.initControls(this.layControls(pid, layout), pid);
		},
		initDom : function(ctl, pid) {
			// 检查DOM是否存在，不存在则创建
			var domName = ctl.type;
			var attr = ctl.attr;
			var style = ctl.style;
			var InnerHTML = ctl.InnerHTML;
			var domOption = "";

			if (style == undefined)
				style = "";
			if (attr == undefined)
				attr = "";
			if (InnerHTML == undefined)
				InnerHTML = "";

			switch (ctl.type) {
			// 网页基本元素以ctl.type默认
			case 'form':
				if (ctl.option.method == undefined)
					ctl.option.method = "POST";
				attr = attr + " method='" + ctl.option.method + "' ";
				break;
			// EasyUI控件元素(布局)
			case 'easyui-datagrid':
			case 'easyui-tabs':
			case 'easyui-accordion':
			case 'easyui-layout':
				domName = 'div';
				break;
			// EasyUI控件元素(菜单按钮)
			case 'easyui-menu':
				domName = 'div';
				break;
			case 'easyui-linkbutton':
			case 'easyui-menubutton':
			case 'easyui-splitbutton':
			case 'easyui-switchbutton':
				domName = 'a';
				attr = attr + " href='javascript:void(0)' ";
				break;
			// EasyUI控件元素(表单)
			case 'easyui-validatebox':
			case 'easyui-textbox':
			case 'easyui-combo':// combo
			case 'easyui-numberbox':
			case 'easyui-datebox':
			case 'easyui-datetimebox':
			case 'easyui-datetimespinner':
			case 'easyui-spinner':// spinner
			case 'easyui-numberspinner':
			case 'easyui-timespinner':
			case 'easyui-slider':
			case 'easyui-filebox':
				domName = 'input';
				break;
			case 'easyui-combobox':
			case 'easyui-combotree':
			case 'easyui-combogrid ':
				domName = 'select';
				break;
			case 'easyui-calendar ':
				domName = 'div';
				break;
			// EasyUI控件元素(窗口)
			case 'easyui-window':
			case 'easyui-dialog':
				domName = 'div';
				break;

			// EasyUI控件元素(表格与树)
			case 'easyui-datagrid':
			case 'easyui-propertygrid':
			case 'easyui-treegrid':
				domName = 'table';
				break;
			case 'easyui-datalist':
			case 'easyui-tree':
				domName = 'ul';
				break;
			// EasyUI控件元素(扩展)
			case 'easyui-edatagrid':// 可编辑数据表格
			case 'easyui-pivotgrid':// 数据分析表格
				domName = 'table';
				break;
			case 'easyui-etree':// 可编辑树
				domName = 'ul';
				break;
			default:
				domName = ctl.type;
			}
			if (pid != 'body')
				pid = "#" + pid;

			if (attr.length > 0)
				domOption = domOption + attr;
			if (style.length > 0)
				domOption = domOption + " style=\" " + style + "\"";
			$('#fm').find('input[id=xxx]')
			if ($(pid).find('*[id=' + ctl.id + ']').length == 0) {
				//console.log(domOption);
				$(pid).append(
						"<" + domName + " id='" + ctl.id + "' name='" + ctl.id
								+ "' " + domOption + " >" + InnerHTML + "</"
								+ domName + ">");
			}
		},
		layControls : function(pid, layout) {


			if (layout.columns == undefined) layout.columns = 2;
			if (layout.rowHeight == undefined) layout.rowHeight = 28;
			if (layout.captionWidth == undefined) layout.captionWidth = 80;
			if (layout.fieldWidth == undefined) layout.fieldWidth = 200;
			if (layout.captionSuffix == undefined) layout.captionSuffix = "";
			if (layout.textAlign == undefined) layout.textAlign = "right";


			for (var i = 0; i < layout.controls.length; i++) {
				if (layout.controls[i].captionVisible == undefined) layout.controls[i].captionVisible = true;

				if (layout.controls[i].colspan == undefined) layout.controls[i].colspan = 1;
				if (layout.controls[i].colspan > layout.columns) layout.controls[i].colspan = layout.columns;

				if (layout.controls[i].option == undefined) layout.controls[i].option = {};
				if (layout.controls[i].option.width == undefined) {
					if (layout.controls[i].captionVisible)
						layout.controls[i].option.width = (layout.captionWidth + layout.fieldWidth) * layout.controls[i].colspan - layout.captionWidth;
					else
						layout.controls[i].option.width = (layout.captionWidth + layout.fieldWidth) * layout.controls[i].colspan;
				}
				if (layout.controls[i].option.height == undefined) layout.controls[i].option.height = layout.fieldHeight;

			}
			var tbwidth = (layout.captionWidth + layout.fieldWidth ) * layout.columns;

			var ret = {
				id : 'table' + pid,
				isExternal : true,
				type : 'table',
				attr:' cellspacing="0" ',
				style : " font-size: 12px;margin:0 auto;width:" + tbwidth  + "px ",
				controls : []
			};

			var rets=[];

			var pos = 0;
			var row = {};
			for (var i = 0; i < layout.controls.length;) {
				if(layout.controls[i].colspan==0) {
					rets[rets.length]= layout.controls[i];
					i++;
					continue;
				}
				//新行增加<TR>
				if (pos == 0) {
					ret.controls[ret.controls.length] = {
						id : 'tr_' + pid + ret.controls.length,
						isExternal : true,
						type : 'tr',
						style : "  width:" + tbwidth + "px; height:"
								+ layout.rowHeight + "px ",
						controls : []
					};
					row = ret.controls[ret.controls.length - 1];
				}


				if (pos + layout.controls[i].colspan -1 < layout.columns) {
					var captionCols=1;
					if(layout.controls[i].captionVisible ){
						row.controls[row.controls.length] = {
							id : 'td_caption_' + pid + ret.controls.length + '_'
									+ (pos * 2),
							isExternal : true,
							attr:'align="'+layout.textAlign+'" ',
							type : 'td',style:'padding:0;width:' +layout.captionWidth+'px;',
							//InnerHTML : layout.controls[i].caption + layout.captionSuffix
							 controls : [ {
								 id : 'span_caption_' + pid + ret.controls.length + '_' + (pos * 2),
								 isExternal : true,
								 style:'padding:0 8px ;',
								 type : 'div',
								 InnerHTML : layout.controls[i].caption + layout.captionSuffix
							 } ]
						};
					}
					else captionCols=0;


					var insCtl=[layout.controls[i]];
					if( layout.controls[i].controls!=undefined) insCtl= layout.controls[i].controls;

					row.controls[row.controls.length] = {
						id : 'td_field_' + pid + ret.controls.length + '_'
								+ (pos * 2 + 1),
						isExternal : true,
						type : 'td',style:'padding:0px;line-height:' + layout.rowHeight + 'px',
						attr : " colspan="
								+ (layout.controls[i].colspan * 2 - captionCols) + " ",
						controls :insCtl
					};

					pos = pos + layout.controls[i].colspan;
					i++;
				} else {
					row.controls[row.controls.length] = {
						id : 'td_caption_' + pid + ret.controls.length + '_'
						+ (pos * 2),
						isExternal : true,
						type : 'td',
						//style:'background-color: antiquewhite',
						attr : " colspan="
						+ ((layout.columns-pos)*2) + " ",
						width : layout.captionWidth,
						controls : []
					};
					pos=0;
					/*
					row.controls[row.controls.length] = {
						id : 'td_caption_' + pid + ret.controls.length + '_'
								+ (pos * 2),
						isExternal : true,
						type : 'td',style:'background-color: antiquewhite',
						width : layout.captionWidth,
						controls : []
					};
					row.controls[row.controls.length] = {
						id : 'td_field_' + pid + ret.controls.length + '_'
								+ (pos * 2 + 1),
						isExternal : true,
						type : 'td',style:'background-color: black',
						width : layout.fieldWidth,
						controls : []
					};
					pos++;*/
				}
				if (pos >= layout.columns)pos = 0;
			}

			//填充未满CELL
			if(pos < layout.columns)
			{
				row.controls[row.controls.length] = {
					id : 'td_caption_' + pid + ret.controls.length + '_'
					+ (pos * 2),
					isExternal : true,
					type : 'td',
					//style:'background-color: antiquewhite',
					attr : " colspan="
					+ ((layout.columns-pos)*2) + " ",
					width : layout.captionWidth,
					controls : []
				};

			}

			rets[rets.length]= ret;

			return   rets ;
		},
		initOption : function(type, option) {
			var opt = option;
			if (opt == undefined)
				opt = {};
			switch (type) {
			case 'easyui-datagrid':
				if (opt.fit == undefined)
					opt.fit = true;
				if (opt.pageList == undefined)
					opt.pageList = [ 10, 15, 20, 30 ];
				if (opt.pageSize == undefined)
					opt.pageSize = 20;
				if (opt.pagination == undefined)
					opt.pagination = true;
				if (opt.rownumbers == undefined)
					opt.rownumbers = true;
				if (opt.nowrap == undefined)
					opt.nowrap = true;
				if (opt.singleSelect == undefined)
					opt.singleSelect = true;
			}
			return opt;
		},

		loadData : function(pid, data) {
			var es = $("#" + pid).find("span");

			for (var i = 0; i < es.length; i++) {

				var dataid = es[i].getAttribute("id");
				try {
					eval(' if(data.' + dataid + '!=undefined) es[i].innerText=data.' + dataid + ';');
				}catch(e){;}
			}
		}
	}
}();

